﻿using System;
using System.Collections.Generic;
using System.IO;
using wojilu.Apps.Qycms.Domain;
using wojilu.Web.Mvc;

namespace wojilu.Web.Controller.Htmls
{
    public class ReadMaker : HtmlMaker
    {
        private static readonly ILog logger = LogManager.GetLogger(typeof(ReadMaker));

        private Document _post;

        protected override string GetDir(String lng)
        {
            return strUtil.Join(sys.Path.Root + YBBCommon.GetConfigStr("file_htmldir"), lng + "/");
        }

        public virtual void Process(Document row, String lng)
        {
            CheckDir(lng);
            String html = String.Empty;
            String lnkNormal = String.Empty;

            switch (lng)
            {
                case "cn":
                    lnkNormal = Link.To(new Cn.Article.ReadController().Show, row.Id);
                    break;

                case "big":
                    lnkNormal = Link.To(new Big5.Article.ReadController().Show, row.Id);
                    break;

                case "en":
                    lnkNormal = Link.To(new En.Article.ReadController().Show, row.Id);
                    break;
            }
            List<String> pagedUrls = new List<String>(); // 翻页的链接
            var dirpath = strUtil.Join(GetDir(lng), row.filepath + "/") + row.filename + "." + YBBCommon.GetConfigStr("file_fileex");
            html = makeHtml(lnkNormal, pagedUrls);
            FileSystemObject.WriteFile(PathHelper.Map(dirpath), html);
            if (pagedUrls.Count > 0)
            {
                makeDetailPages(row, pagedUrls, lng);
            }
        }

        // 处理需要翻页的详细页
        private void makeDetailPages(Document post, List<String> pagedUrls, String lng)
        {
            _post = post;
            foreach (String url in pagedUrls)
            {
                String addrPaged = url;
                String htmlPaged = makeHtml(addrPaged);
                String htmlPath = getPath(post, PageHelper.GetPageNoByUrl(url), lng);
                file.Write(htmlPath, htmlPaged);
                logger.Info("make html done=>" + htmlPath);
            }
        }

        private string getPath(Document post, int page, String lng)
        {
            return Path.Combine(GetDir(lng), post.Id + "_" + page + ".html");
        }

    }
}
